import React, { Component, useRef, useEffect, useState } from "react";
import { Drawer, Button, message, Select, Input, Space, Affix, Table, Popover, Form, DatePicker } from 'antd';
import { ArrowLeftOutlined} from '@ant-design/icons';
import { CmdbContent, HcpTableFilterBar, CmdbHeader , TableColumsProperties, TempImportModal, HcpTableTooltip, useModelList} from "@/components";
import moment from 'moment';
import CreateBusiness from "./create";
import DeleteBusiness from './delete';
import cmdbres from "@/data/cmdbres";
import request, { exportFile } from "@/utils/request";
import hcpUtils from "@/utils/hcpUtils";

const { RangePicker } = DatePicker;
const BusinessManege = ({ history, match, location }) => {
    const [form] = Form.useForm();
    const [properties, setProperties] = useState({});
    const [loading, setLoading] = useState(false);
    const [placement, setPlacement] = useState('right');
    const [tableData, setTableData] = useState([]);
    const [row, setRow] = useState({});
    const [tableHeaderFields, setTableHeaderFields] = useState([]);
    const [checkedFields, setCheckedFields] = useState([]);
    const [unCheckedFields, setUnCheckedFields] = useState([]);
    const [defaultCheckedFields, setDefaultCheckedFields] = useState([]);
    const [defaultUnCheckedFields, setDefaultUnCheckedFields] = useState([]);
    const [visible, setVisible] = useState(false);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [query_key, setQuery_key] = useState("");  //命名采用下划线方式方便直接传值
    const [query_keyType, setQuery_keyType] = useState("");
    const [inputHolderMess, setInputHolderMess] = useState("");
    const [fieldsEnum , setFieldsEnum] =  useState([]);
    const [module] = useModelList("biz"); // 查找模型
    const state =  location.state;
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [showAddModal, setShowAddModal] = useState(false);

    const getTableData = async (params = { current: 1, pageSize: 10 }) => {
        setSelectedRowKeys([]);
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryBizList,
                data: {
                    pageSize: params.pageSize,
                    pageNumber: params.current,
                    ...properties,
                    sort:{
                        bizCode:"ASC",
                        createTime:"DESC"
                    },
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total,
                }));
                let arr = [];
                res.data.map((item, index) => {
                    if(item.cm_unid !=  "0") {
                        item.key = index;
                        enumTranslate(item);
                        arr.push(item);
                    }
                });
                setTableData(arr);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        }
    };

    const onFinish = () => {
        setRow({});
        let query_value = form.getFieldValue([query_key]);
        if(query_keyType == 'date') {
            setProperties({
                queryFilter: {
                    GTE: {// 大于等于号（>=）
                        [query_key]: query_value?.[0] ? query_value[0].format('YYYY-MM-DD') : undefined
                    },
                    LTE: {// 小于等于号(<=)
                        [query_key]: query_value?.[1] ? query_value[1].format('YYYY-MM-DD') : undefined
                    }
                }
            })
        } else if(query_keyType == 'datetime') {
            if(!(query_value && query_value.length)) {
                setProperties({});
                return;
            }
            setProperties({
                timeConditions:[{
                    field: query_key,
                    start: query_value[0].format('YYYY-MM-DD HH:mm:ss'),
                    end: query_value[1].format('YYYY-MM-DD HH:mm:ss')
                }]

            })
        } else {
            setProperties({
                queryFilter: { LIKE: { [query_key]: query_value } }
            })
        }
    };

    useEffect(() => {
        if(properties && tableHeaderFields.length>0) {
            getTableData();
        }
    }, [properties, tableHeaderFields]);

    const enumTranslate = (data) => {
        for(let fieldKey in data) {
            if(fieldsEnum[fieldKey]) {
                let enumValue = fieldsEnum[fieldKey];
                const translateState =  enumValue[data[fieldKey]];
                if(translateState) {
                    data[fieldKey] = enumValue[data[fieldKey]];
                }
            }
        }
    }

    const queryTableHeaders = async () => {
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryTableHeader,
                params: {
                    cm_module_id: module.cmModuleId
                },
            });
            setLoading(false);
            if (res && res.code == 200) {
                const fieldData = res.data;
                const checkedArrs = [];
                const unCheckedArrs = [];
                let enumValues = {};
                let cmId = {};
                fieldData.fields.map((item, index) => {
                    let field = {
                        ...item,
                        key: item.propertyKey,
                        title: item.unit ? `${item.propertyName}(${item.unit})` : item.propertyName,
                        dataIndex: item.propertyKey,
                        width: 130,
                        copyable: true,
                        ellipsis: true,
                    };

                    if(['date', 'datetime'].includes(item.propertyType)) {
                        const formString = item.propertyType == 'date' ? 'YYYY-MM-DD': 'YYYY-MM-DD HH:mm:ss';
                        field.render =  (text, record) => hcpUtils.timeConversion(text, formString)
                    }

                    if(item.propertyType == "enum" && field.woIsHidden === 0) {
                        let enumValueStr =item.propertyEnumValue.replace(/'/g,"\"");
                        enumValues[field.key] = JSON.parse(enumValueStr);
                    }
                    setFieldsEnum(enumValues);

                    if(item.propertyKey == 'biz_name') {
                        cmId = field;
                        return;
                    }
                    if (field.woIsHidden === 0) {
                        checkedArrs.push(field);
                    } else {
                        unCheckedArrs.push(field);
                    }
                });


                const noOperCheckedArrs = [cmId, ...checkedArrs];
                const operField = {
                    title: "操作",
                    fixed: 'right',
                    width: 120,
                    woIsSystem: 1,
                    woIsHidden: 1,
                    render: (text, record, index) => {
                        return (
                        <Space key={record.cm_unid}>
                            <a
                                onClick={() => {
                                    setIsBath(false);
                                    setRow(record);
                                    setShowAddModal(true);
                                }}
                            >修改</a>
                            <a
                                onClick={() => {
                                    setIsBath(false);
                                    setRow(record);
                                    setShowDeleteModal(true);
                                }}
                            >删除</a>
                        </Space>
                        )
                    }
                }
                checkedArrs.push(operField);
                setTableHeaderFields([{
                    ...cmId,
                    render: (text, record) => (
                        <HcpTableTooltip
                            label="ID"
                            showValue={record.biz_name}
                            copyValue={record.biz_name}
                            onClick={() => {
                                history.push({
                                    pathname: "/resource/catalog/biz/detail/" + module.cmModuleId,
                                    state: {
                                        data:record,
                                        columns: JSON.stringify(noOperCheckedArrs) ,
                                        moduleData: module,
                                        goBackUrl: "/resource/catalog/biz"}
                                });
                            }}
                        />
                    )},...checkedArrs
                ])
                setCheckedFields(noOperCheckedArrs);
                setDefaultCheckedFields([...noOperCheckedArrs])
                setUnCheckedFields(unCheckedArrs);
                setDefaultUnCheckedFields([...unCheckedArrs]);
            } else {
                setCheckedFields([]);
                setUnCheckedFields([]);
            }
        } catch (error) {
            console.log("getTableData -> error", error);
        }
    }

    const queryUncheckedField = async (value) => {
        try {
            const res = await request({
                ...cmdbres.queryTableHeader,
                params: {
                    cm_module_id: module?.cmModuleId,
                    property_name: value
                },
            });
            if (res && res.code == 200) {
                const fieldData = res.data;
                const unCheckedArrs = [];
                fieldData.fields.map((item, index) => {
                    let field = {
                        ...item,
                        key: index,
                        title: item.propertyName,
                        dataIndex: item.propertyKey,
                        width: 130,
                        copyable: true,
                        ellipsis: true,
                    };
                    if (field.woIsHidden === 1) {
                        unCheckedArrs.push(field);
                    }
                });
                setUnCheckedFields(unCheckedArrs);
            } else {
                setUnCheckedFields([]);
            }
        } catch (error) {
            console.log("getTableData -> error", error);
        }
    }

    useEffect(() => {
        if(module && module.cmModuleId) {
            queryTableHeaders();
        }
    }, [module]);


    const setSelectProperty = (field) => {
        setQuery_key(field?.propertyKey);
        setQuery_keyType(field?.propertyType);
        setInputHolderMess("请输入" + (field?.propertyName || ""));
    }

    useEffect(() => {
        if(!query_key && checkedFields.length>0) {
            setSelectProperty(checkedFields[0]);
        }
    }, [query_key]);

    useEffect(() => {
        if (checkedFields.length > 0 && checkedFields[0].propertyKey != query_key) {
            setSelectProperty(checkedFields[0]);
        }
    }, [checkedFields]);

    const resetScreen = () => {
        form.resetFields();
        if (checkedFields.length > 0) {
            const field = checkedFields[0];
            form.setFieldsValue({
                "query_key": field?.propertyKey
            })
            setSelectProperty(field);
        }
    };

    const onSelectChange = (propertyKey) => {
        const checkSelect = checkedFields.find(function(val){
            return val.propertyKey == propertyKey;
        });
        setSelectProperty(checkSelect);
    }

    const handleTableChange = (e) => {
        getTableData(e);
    };

    const [isBath, setIsBath] = useState(false);
    const rowSelection = {
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
            if(selectedRowKeys.length > 0) {
                setIsBath(true);
            }else {
                setIsBath(false);
            }
            setSelectedRowKeys(selectedRowKeys);
        },
    };

    const updateFields = () => {
        setVisible(true)
    }
    /**设置表格列组件里面的方法----------开始 */
    const onClose = () => {
        setVisible(false);
        onReset();
    }

    const onReset = () => {
        setCheckedFields(defaultCheckedFields);
        setUnCheckedFields(defaultUnCheckedFields);
    }

    const onOk = async () =>  {
        setLoading(true);
        let showFields = []
        for(let item of checkedFields) {
            showFields.push(item.propertyKey)
        }
		let param =  {
			namespace: "default",  //先传默认
            cm_module_id: module?.cmModuleId,
            show_fields: showFields
		}

        const res = await request({
			...cmdbres.updateFieldshow,
			data: param
		});
		setLoading(false);
		if (res && res.code == 200) {
			setVisible(false);
			message.success( "修改成功！");
            queryTableHeaders();
		} else {
			if(res) message.error(res.msg);
		}

    }

    const updateUncheckedFields = (item) => {
        const newUnCheckedFields = unCheckedFields.filter(function(val){
            return val.propertyKey != item.propertyKey;
        });
        var newCheckedFields = checkedFields;
        newCheckedFields.push(item);
        setCheckedFields(newCheckedFields);
        setUnCheckedFields(newUnCheckedFields);
    }

    const updateCheckedFields = (item) => {
        const newFields = checkedFields.filter(function(val){
            return val.propertyKey != item.propertyKey;
        });
        var newUnCheckedFields = unCheckedFields;
        newUnCheckedFields.push(item);
        setCheckedFields(newFields);
        setUnCheckedFields(newUnCheckedFields);
    }
    /**设置表格列组件里面的方法----------结束 */

    return (
        <CmdbContent>
            <div className="breadcrumbs-layout">
                {state && state.source == 'resource' ?
                    <h3>
                        <ArrowLeftOutlined
                            onClick={() => { history.push({
                                pathname: '/resource/catalog',
                            });}}
                        />
                        {`${state.moduleName || '-'}`}
                    </h3>
                    : <h3> 资源业务</h3>
                }
            </div>
            <div className="resource-catalog-pane" style={{backgroundColor: "#fff", padding: "10px"}}>
                <div className="session-bar">
                    <section style={{width: "50%", float: "left", padding: "5px 10px 15px 0"}}>
                        <Space>
                            <Button type="primary" onClick={() => {setRow(); setShowAddModal(true);}}>
                                新建
                            </Button>
                            <Button type="primary" onClick={() => {getTableData()}} >
                                刷新
                            </Button>
                        </Space>
                    </section>
                    <section className="hcp__search__collapse hcp_search_bar" style={{width: "50%", textAlign: "right",  paddingTop: "5px"}}>
                        <section className="hcp__form">
                            <HcpTableFilterBar
                                form={form}
                                resetClick={resetScreen}
                                onSearch={onFinish}
                                updateFields={updateFields}
                                items={[
                                    {
                                    field: { query_key },
                                    component: (
                                        <Input.Group compact style={{ display: "flex"}}>
                                        <Form.Item name="query_key" noStyle>
                                            {
                                                query_key ?
                                                <Select
                                                    style={{ minWidth: '110px', textAlign: "left" }}
                                                    defaultValue={query_key}
                                                    onChange={onSelectChange}
                                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                                >
                                                    {tableHeaderFields && tableHeaderFields.length > 0 ? checkedFields.map((item, index) => {
                                                        return (
                                                            <Select.Option value={item.propertyKey} defaultValue={checkedFields[0].propertyKey} key={index}>{item.propertyName}</Select.Option>
                                                        )
                                                    }): null}
                                                </Select> : null
                                            }

                                        </Form.Item>
                                        {tableHeaderFields && tableHeaderFields.length > 0 ? tableHeaderFields.map((item, index) => {
                                            return (
                                                <div key={index} style={{ margin: 0 }}>
                                                    {query_key == item.propertyKey ? (
                                                        item.propertyType == 'date' ?
                                                        <Form.Item
                                                            key={item.propertyKey}
                                                            style={{ width: 190, maxWidth: 190 }}
                                                            name={item.propertyKey}
                                                        >
                                                            <RangePicker format="YYYY-MM-DD"/>
                                                        </Form.Item>
                                                        :
                                                        item.propertyType == 'datetime' ?
                                                        <Form.Item
                                                            key={item.propertyKey}
                                                            style={{ width: 190, maxWidth: 190 }}
                                                            name={item.propertyKey}
                                                        >
                                                            <RangePicker showTime format="YYYY-MM-DD HH:mm:ss"/>
                                                        </Form.Item>
                                                        :
                                                        <Form.Item
                                                            key={item.propertyKey}
                                                            style={{ width: 190, maxWidth: 190 }}
                                                            name={item.propertyKey}
                                                        >
                                                            <Input allowClear maxLength={50} placeholder={inputHolderMess} />
                                                        </Form.Item>
                                                    ) : null}
                                                </div>
                                            )
                                        }): null}
                                        </Input.Group>
                                    )
                                    }
                                ]}
                            />
                        </section>
                    </section>
                </div>
                <Table
                    rowKey={record => record.cm_unid}
                    // rowSelection={{ ...rowSelection}}
                    columns={tableHeaderFields}
                    loading={loading}
                    dataSource={tableData}
                    scroll={{ x: '100%' }}
                    pagination={{
                        showSizeChanger: true,
                        showQuickJumper: {
                            goButton: (
                                <Button style={{ margin: "0 10px" }}>确定</Button>
                            ),
                        },
                        ...pagination,
                    }}
                    onChange={handleTableChange}
                    hideSetting
                />
            </div>
            {showAddModal&&<CreateBusiness
                onCreateFinish={getTableData}
                visible={showAddModal}
                setVisible={setShowAddModal}
                info={row}
                cmModuleId={module?.cmModuleId}
            />}
            <DeleteBusiness
                onDeleteFinish={getTableData}
                visible={showDeleteModal}
                setVisible={setShowDeleteModal}
                info={row}
            />
            {checkedFields.length > 0  ?
            <TableColumsProperties
                placement={placement}
                drawerWidth={600}
                checkedFields={checkedFields}
                setCheckedFields={setCheckedFields}
                unCheckedFields={unCheckedFields}
                setUnCheckedFields={setUnCheckedFields}
                onOk={onOk}
                onClose={onClose}
                onSearch={queryUncheckedField}
                onUpdateCheckedFields={updateCheckedFields}
                onUpdateUncheckedFields={updateUncheckedFields}
                onReset={onReset}
                visible={visible}
            />: null}
        </CmdbContent>
    );
};

export default BusinessManege;
